<template>
  <div class="pSlide page-miH page-bgBack">
    <a-layout>
      <a-layout-sider :width="225" style="border-right: 1px solid #e8e8e8">
        <!-- title -->
        <div class="pSlide-title" @mouseenter="addIcon = true" @mouseleave="addIcon = false" @click.stop="getAllList">
          审批分组({{ allList }})
          <a-icon class="mg_l81" style="font-weight: 500" type="plus" @click.stop="newGroup" />
        </div>
        <!-- sider -->
        <a-menu style="min-height: 500px" v-model="menuKey">
          <a-menu-item
            v-for="item in groupList"
            :key="item.id"
            @mouseenter="act = item.id"
            @mouseleave="act = false"
            @click="getApprovalList(item)"
          >
            <a-row type="flex" align="middle" justify="space-between">
              <a-col :span="20" class="ove">
                <a-tooltip placement="rightTop">
                  <template slot="title">
                    <span>{{ `${item.groupName}(${item.approFlowNum})` }}</span>
                  </template>
                  <span>{{ `${item.groupName}(${item.approFlowNum})` }}</span>
                </a-tooltip>
              </a-col>
              <a-col>
                <a-icon v-show="act == item.id" type="setting" @click.stop="setting(item)" />
              </a-col>
            </a-row>
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      <!-- container -->
      <a-layout class="mg_l20">
        <a-row type="flex" class="lay-head">
          <a-col>
            <div style="display: flex">
              <a-button type="primary" icon="plus" style="margin-right: 10px" @click="createApproval(null)">新建审批</a-button>
              <a-button v-if="isContainByString('approvalAdmin')" type="primary" @click="showIssueModa">下发审批</a-button>
            </div>
          </a-col>
          <a-col class="mg_l_o">
            <a-input-search placeholder="请输入" style="width: 200px" allowClear @search="onSearch" />
          </a-col>
        </a-row>
        <a-layout-content>
          <a-table :pagination="pagination" :dataSource="data" rowKey="id" style="margin-top: 20px">
            <a-table-column title="审批列表">
              <template slot-scope="text">
                <a-row type="flex" align="middle">
                  <a-col class="icon mg_r10">
                    <img style="width: 48px" :src="text.icon" alt="加载失败" />
                  </a-col>
                  <a-col>
                    <a-row class="title1">{{ text.typeName }}</a-row>
                    <a-row class="subTitle">{{ text.typeDesc }}</a-row>
                  </a-col>
                </a-row>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="200">
              <template slot-scope="text">
                <a-popover title="编辑" trigger="focus">
                  <template slot="content">
                    <a-button type="small" style="margin-right: 5px" @click="createApproval(text.id)">编辑详情</a-button>
                    <a-button type="small" @click="deleteUseItem(text)">删除</a-button>
                  </template>
                  <a-button>编辑</a-button>
                </a-popover>
                <a-switch
                  v-if="!isContainByString('approvalAdmin')"
                  v-model="text.inUse"
                  checked-children="已启用"
                  un-checked-children="未启用"
                  style="border-radius: 4px; margin-left: 24px"
                  @change="onChangeUse($event, text)"
                />
              </template>
            </a-table-column>
          </a-table>
        </a-layout-content>
      </a-layout>
    </a-layout>
    <NewGroup :new-group-options="newGroupOptions" />
    <!-- 下发模板 -->
    <a-modal
      :visible="issueModalVisible"
      title="下发审批模版"
      width="538px"
      :destroy-on-close="true"
      @ok="confirmIssueModal"
      @cancel="handleCancelIssueModal"
    >
      <a-row>
        <a-col :span="12">
          <span>请选择审批模板</span>
          <a-tree-select
            :treeData="contractData"
            :replaceFields="replaceFields"
            :filterTreeNode="false"
            treeCheckable
            placeholder="请选择审批模板"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow-y: auto"
            @search="treeSearch2"
            @change="treeSelectChange"
          />
        </a-col>
        <a-col :span="12">
          <span>请选择下发用工单位</span>
          <a-tree-select
            :value="companyList"
            :treeData="dataList"
            :filterTreeNode="false"
            treeCheckable
            placeholder="请选择用工单位"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
            @search="treeSearch"
            @change="companySelectChange"
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import NewGroup from "./components/new-group";
import { findCompanyGroup } from "@/api/company/contract";
import { Project, ProjectApi } from "@/api/project/new-index";
import { isContainByString } from "@/utils/index";
import { saveIssuedApproFlow, selectTreeByCompanyId } from "./editor/api";
import { formatCompanyTree } from "@/utils/tools";
export default {
  components: { NewGroup },
  data() {
    return {
      menuKey: [],
      allList: 0,
      // 添加图标
      addIcon: false,
      // 设置图标
      act: false,
      companyId: this.$store.state.hr.companyId,
      id: null,
      groupList: [],
      newGroupOptions: null,
      data: [],
      query: {
        groupId: "",
        typeName: ""
      },
      isContainByString,
      dataList: [],
      issueModalVisible: false,
      // 下发选择框数据
      contractData: [],
      // 已选的模板数据
      contractList: [],
      // 已选的公司数据
      companyList: [],
      replaceFields: {
        children: "approFlowVOList",
        key: "id",
        value: "id",
        title: "typeName"
      },
      issuedAppro: {},
      pagination: {
        pageNo: 1,
        pageSize: 20,
        pageSizeOptions: ["10", "20", "50", "100"], // 3,4 有
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    };
  },
  created() {
    this.findCompanyGroup();
  },
  mounted() {
    this.getGroupList();
    this.getAllList();
    if (isContainByString("approvalAdmin")) {
      // 调用查询下发公司列表
      this.selectTreeByCompanyId();
    }
    const st = this.$route.query.operateFromShortcut;
    if (st === "chuangjianshenpifenzu") {
      this.newGroup();
    }
  },
  methods: {
    companySelectChange(companyKeys) {
      this.companyList = companyKeys.filter((item) => item.includes("_company_"));
    },
    treeSearch2(e) {
      this.selectTreeByCompanyId(e);
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = formatCompanyTree(res.data);
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 启用禁用
    onChangeUse(val, text) {
      if (val) {
        this.useItem(text);
      } else {
        this.stopUseItem(text);
      }
    },
    // 删除全部审批
    deleteApproval() {
      const approvalAdmin = isContainByString("approvalAdmin")
        ? "0"
        : isContainByString("defaultTransferAccounts")
        ? "defaultTransferAccounts"
        : this.companyId;
      Project({
        url: ProjectApi.deleteAllApp + approvalAdmin,
        method: "DELETE"
      });
    },
    // 删除某个审批流程
    deleteUseItem(item) {
      this.$confirm({
        title: "确定删除?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          Project({
            url: ProjectApi.baseSetDetail + item.id,
            method: "DELETE"
          }).then((data) => {
            if (data.success) {
              this.$notification["success"]({ message: "删除成功" });
              this.getGroupList();
              this.getAllList();
            }
          });
        }
      });
    },
    // 启用某个审批流程
    useItem(item) {
      Project({ url: ProjectApi.useListItem + item.id, method: "PUT" }).then((data) => {
        if (data.success) {
          this.$notification["success"]({ message: "修改成功" });
        }
      });
    },
    // 停用某个审批流程
    stopUseItem(item) {
      Project({
        url: ProjectApi.stopUseListItem + item.id,
        method: "PUT"
      }).then((data) => {
        if (data.success) {
          this.$notification["success"]({ message: "修改成功" });
        }
      });
    },
    /* 获取分组列表 */
    getGroupList() {
      const approvalAdmin = isContainByString("approvalAdmin")
        ? "0"
        : isContainByString("defaultTransferAccounts")
        ? "defaultTransferAccounts"
        : this.companyId;
      Project({
        url: ProjectApi.groupList + approvalAdmin + `/hr`
      }).then(({ data }) => {
        this.groupList = data;
      });
    },
    /* 获取审批列表查询的 */
    getApprovalList(item) {
      this.query.groupId = item.id;
      Project({
        url: ProjectApi.listQuery + item.id,
        params: {
          moduleType: "hr"
        }
      }).then(({ data }) => {
        this.data = [];
        this.data = data;
        this.pagination.total = data.length;
      });
    },
    // 获取总的审批列表
    getAllList() {
      this.menuKey = [];
      this.query = {};
      const approvalAdmin = isContainByString("approvalAdmin")
        ? "0"
        : isContainByString("defaultTransferAccounts")
        ? "defaultTransferAccounts"
        : this.companyId;
      Project({
        url: ProjectApi.allList + approvalAdmin + `/hr`,
        params: {
          moduleType: "hr"
        }
      }).then(({ data }) => {
        this.data = [];
        this.data = data;
        this.allList = data.length;
        this.pagination.total = data.length;
      });
    },
    /* 搜索 */
    onSearch(e) {
      this.query.typeName = e;
      const approvalAdmin = isContainByString("approvalAdmin")
        ? "0"
        : isContainByString("defaultTransferAccounts")
        ? "defaultTransferAccounts"
        : this.companyId;
      Project({
        url: ProjectApi.allList + approvalAdmin + `/hr`,
        params: { ...this.query, moduleType: "hr" }
      }).then(({ data }) => {
        this.data = [];
        this.data = data;
      });
    },
    /* 新建分组 */
    newGroup() {
      const approvalAdmin = isContainByString("approvalAdmin")
        ? "0"
        : isContainByString("defaultTransferAccounts")
        ? "defaultTransferAccounts"
        : this.companyId;
      this.newGroupOptions = {
        show: true,
        obj: {
          title: "新建审批分组",
          subTitle: "新建审批分组名称",
          companyId: approvalAdmin,
          moduleType: "hr"
        }
      };
    },
    /* 设置 */
    setting(item) {
      this.newGroupOptions = {
        show: true,
        obj: {
          title: "修改审批分组",
          subTitle: "修改审批分组名称",
          ...item
        }
      };
    },
    /* 创建新审批 */
    createApproval(id) {
      if (id) {
        if (isContainByString("defaultTransferAccounts")) {
          this.$router.push({
            path: `/newApproval?defaultTransferAccounts`,
            query: { id }
          });
        } else {
          this.$router.push({
            path: `/${isContainByString("approvalAdmin") ? "newApprovalAdmin" : "newApproval"}`,
            query: { id }
          });
        }
      } else {
        if (isContainByString("defaultTransferAccounts")) {
          this.$router.push({
            path: `/newApproval?defaultTransferAccounts`
          });
        } else {
          this.$router.push(`/${isContainByString("approvalAdmin") ? "newApprovalAdmin" : "newApproval"}`);
        }
      }
    },
    selectTreeByCompanyId(e) {
      selectTreeByCompanyId({
        name: e || null,
        companyId: isContainByString("approvalAdmin")
          ? "0"
          : isContainByString("defaultTransferAccounts")
          ? "defaultTransferAccounts"
          : this.companyId
      })
        .then((res) => {
          const cJsonString = JSON.stringify(res.data);
          this.contractData = JSON.parse(cJsonString.replaceAll("groupName", "typeName"));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 下发接口
    saveIssuedApproFlow() {
      saveIssuedApproFlow(this.issuedAppro)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 方法
    confirmIssueModal() {
      // TODO 下发接口
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的审批模板"
        });
        return;
      }
      if (this.contractList.length > 0) {
        const companyArr = Array.from(new Set(this.companyList.map((item) => item.split("_")[2])));
        this.issuedAppro = {
          approFlowInforList: this.contractList,
          companyIds: Array.from(new Set(companyArr))
        };
      }
      this.saveIssuedApproFlow();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
    },
    showIssueModa() {
      this.issueModalVisible = true;
    },
    treeSelectChange(value, label, extra) {
      this.contractList = [];
      this.contractData.forEach((item) => {
        const categoryListVOList = item.approFlowVOList;
        if (categoryListVOList && categoryListVOList.length > 0) {
          item.approFlowVOList.forEach((itemItem) => {
            // this.contractList.push
            if (value.indexOf(itemItem.id) !== -1) {
              const itemObj = { groupName: item.typeName, approFlowId: "" };
              itemObj.approFlowId = itemItem.id;
              this.contractList.push(itemObj);
            }
          });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.lay-head {
  border-bottom: 1px solid #e8e8e8;
  padding: 0 0 20px 0;
}
.pSlide-title {
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 1);
  padding-left: 14px;
  cursor: pointer;
}
.title1 {
  font-size: 14px;
  color: rgba(37, 37, 37, 1);
  line-height: 20px;
}

.subTitle {
  font-size: 12px;
  color: #595959;
  line-height: 18px;
}
.s {
  display: inline-block;
  width: 64px;
  line-height: 32px;
  text-align: center;
}
.red {
  color: red;
}
.green {
  color: green;
}
</style>
